# encoding: utf-8
import os
import sys
from datetime import datetime, date, timedelta

import django
from django.utils import timezone
from django.db.models import Count

APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(APP_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'traffic.settings')
django.setup()
from core.models import Host, TrafficLog


def distinct(started, ended):
    if started:
        if ended:
            logs = TrafficLog.objects.filter(isvalid=True, date__gte=started, date__lte=ended).order_by('-date')
        else:
            logs = TrafficLog.objects.filter(isvalid=True, date__gte=started).order_by('-date')
    else:
        logs = TrafficLog.objects.all().order_by('-date')
    dgs = logs.values('port_id', 'date').annotate(Count('date'))
    for dict_ in dgs:
        id = dict_.get('port_id')
        da = dict_.get('date')
        dc = dict_.get('date__count')
        if dc > 1:
            print('重复数据 port: {0}  {1} / {2}'.format(id, da, dc))
            plog = logs.filter(port_id=id, date=da).order_by('id')
            plog.exclude(id=plog.first().id).update(isvalid=False)
            min5 = timedelta(seconds=300)
            calc(da - min5, da + min5)


def calc(started, ended):
    now = timezone.now()
    print(now.strftime('%Y-%m-%d %H:%M:%S'))
    hosts = Host.objects.all()
    for host in hosts:
        ports = host.ports.all()
        for port in ports:
            if started:
                if ended:
                    logs = port.traffic_logs.filter(isvalid=True, date__gte=started, date__lte=ended).order_by('-date')
                else:
                    logs = port.traffic_logs.filter(isvalid=True, date__gte=started).order_by('-date')
            else:
                logs = port.traffic_logs.filter(isvalid=True).order_by('-date')

            # dgs = logs.values('date').annotate(Count('date'))
            # for dict_ in dgs:
            #     d = dict_.get('date')
            #     dc = dict_.get('date__count')
            #     if dc > 1:
            #         print('重复数据 port: {0}  {1} / {2}'.format(port.id, d, dc))
            #         isvalid = True
            #         for q in logs.filter(date=d).order_by('id'):
            #             if isvalid:
            #                 isvalid = False
            #             else:
            #                 q.isvalid = isvalid
            #                 q.save()
            # logs = logs.filter(isvalid=True)

            length = logs.count()
            for i, cl in enumerate(logs):
                if i < length - 1:
                    pl = logs[i+1]
                    minus = cl.date - pl.date
                    seconds = minus.total_seconds()  # + minus.days * 86400
                    if seconds < 60:
                        in_bits = 0
                        out_bits = 0
                    else:
                        in_bits = (cl.traffic_in - pl.traffic_in) / seconds * 8
                        out_bits = (cl.traffic_out - pl.traffic_out) / seconds * 8
                    if cl.in_bits != in_bits or cl.out_bits != out_bits:
                        if seconds < 60:
                            cl.isvalid = False
                        cl.in_bits = in_bits
                        cl.out_bits = out_bits
                        cl.save()
                        print('id: {0}  date: {1}  {2}秒'.format(cl.id, cl.date.strftime('%Y-%m-%d %H:%M:%S'), seconds))
    now = timezone.now()
    print(now.strftime('%Y-%m-%d %H:%M:%S'))
    print('ok')


if __name__ == '__main__':
    started = None
    ended = None
    if len(sys.argv) > 1:
        if sys.argv == 'now':
            today = date.today()
            oneday = timedelta(days=1)
            yesterday = (today - oneday).strftime('%Y-%m-%d')
            started, ended = yesterday, yesterday
        if sys.argv[1].find('/') > 0:
            started = datetime.strptime(sys.argv[1], '%Y-%m-%d/%H:%M:%S')
        else:
            started = datetime.strptime(sys.argv[1], '%Y-%m-%d')
        if len(sys.argv) > 2:
            if sys.argv[2].find('/') > 0:
                ended = datetime.strptime(sys.argv[2], '%Y-%m-%d/%H:%M:%S')
            else:
                ended = datetime.strptime(sys.argv[2], '%Y-%m-%d')
        if len(sys.argv) > 3:
            distinct(started, ended)
        else:
            calc(started, ended)
    else:
        print('usage: {0} <start date> [end date] [distinct] \n %Y-%m-%d/%H:%M:%S or %Y-%m-%d \n'.format(sys.argv[0]))
